<?php
namespace app\index\controller;


class Index extends Base
{
    // 首页
    public function index()
    {
        $where = [];
        if (input('?id')){
            $where = [
                'cate_id' => input('id')
            ];
        }

        $articles = model('Article')
            ->where($where)
            ->order('create_time')
            ->paginate(7);
        $catename = model('Category')->where('id', input('id'))->value('catename');

        $viewdata = [
            'articles' => $articles,
            'catename' => $catename,
        ];
        $this->assign($viewdata);
        return view();
    }

    //注册
    public function register()
    {
        if (request()->isAjax()){
            $data = [
                'username' => input('post.username'),
                'nickname' => input('post.nickname'),
                'password' => input('post.password'),
                're_password' => input('post.re_password'),
                'email' => input('post.email'),
                'verify' => input('post.verify'),
            ];
            $result = model('Member')->register($data);
            if ($result == 1){
                $this->success('注册成功', 'index/index/login');
            }else {
                $this->error($result);
            }
        }


        return view();
    }

    // 登录
    public function login()
    {
        if (request()->isAjax()){
            $data = [
                'username' => input('post.username'),
                'password' => input('post.password'),
                'verify' => input('post.verify'),
            ];
            $result = model('Member')->login($data);
            if ($result == 1){
                $this->success('登录成功', 'index/index/index');
            }else {
                $this->error($result);
            }
        }

        return view();
    }


    // 退出登录
    public function logout()
    {
        session(null);
        if (session('?member.id')){
            $this->error('退出失败');
        }else{
            $this->success('退出成功', 'index/index/index');
        }
    }

    // 搜索
    public function search()
    {
        $articles = model('Article')->where('title', 'like','%'.input('keywords').'%')
            ->order('create_time', 'desc')
            ->paginate(7);
        $catename = input('keywords');
        $viewdata = [
            'articles' => $articles,
            'catename' => $catename
        ];
        $this->assign($viewdata);
        return view('index');
    }
}
